package com.sparrow.common.ai.fsm;

public class StateMachine<E> {
    private final E owner;
    private State<E> curState;
    private final StateMachineContext<E> context;

    public StateMachine(E owner, State<E> initialState) {
        this.owner = owner;
        this.curState = initialState;
        this.context = new StateMachineContext<>(owner, this);
    }

    public State<E> getCurState() {
        return curState;
    }

    public void setState(State<E> state) {
        this.curState = state;
    }

    public void changeState(State<E> newState) {
        if (curState != null) {
            curState.exit(context);
        }
        this.curState = newState;
        newState.enter(context);
    }

    public void update() {
        if (curState != null) {
            curState.update(context);
        }
    }

    public boolean isInState(State<E> state) {
        return this.curState != null && this.curState.equals(state);
    }

    public StateMachineContext<E> getContext() {
        return context;
    }
}
